using UnityEngine;
using System.Collections;

public class Laser : MonoBehaviour {
    public float lifeSpan = 5.0f;   //how long the laser will stay alive if it doesn't hit anything, in seconds
    public ParticleSystem paricles;

    private Vector3 velocity;
    private float age;
    private bool canAge = false;
    private string turretName = "";

	// Use this for initialization
	void Start () {
        age = 0;
	}

	// Update is called once per frame
    void Update() {
        if (canAge) age += Time.deltaTime;
        if (age > lifeSpan)
        {
            Debug.Log("Laser::Update(): " + gameObject.name + " died");
            Destroy(gameObject);
        }
        else
            transform.Translate(velocity * Time.deltaTime);
    }

    void OnTriggerEnter(Collider other)
    {
        // Ignore drop shadows
        if (other.gameObject.GetComponent<DropShadow>() != null)
            return;

        if (!other.gameObject.GetComponent<Hazard>() &&
            turretName.Length > 0 && 
            other.gameObject.name != turretName)    //if colliding with a non-hazard, DIE
        {
            Debug.Log("Laser::Update(): " + gameObject.name + " hit " + other.gameObject.name);
            GameObject temp = (GameObject)GameObject.Instantiate(GameObject.Find(paricles.name), gameObject.transform.position, 
                gameObject.transform.rotation);
            temp.transform.Rotate(0, 180, 0);
            temp.GetComponent<ParticleSystem>().Play();
            Destroy(gameObject);
            Destroy(temp, temp.GetComponent<ParticleSystem>().startLifetime);
        }
    }

    public void SetVelocity(float x, float y, float z)
    {
        velocity = new Vector3(x, y, z);
    }

    public void CanAge(bool b)
    {
        canAge = b;
    }

    public void SetTurretName(string s)
    {
        if (s.Length > 0)
            turretName = s;
    }
}
